use sysinfo::{System, ProcessExt, SystemExt};
use prometheus::{Registry, Gauge, TextEncoder};

pub struct PerformanceMonitor {
    registry: Registry,
    cpu_usage: Gauge,
    memory_usage: Gauge,
}

impl PerformanceMonitor {
    pub fn new() -> Self {
        let registry = Registry::new();
        let cpu_usage = Gauge::new("yam_cpu_usage", "CPU usage percentage").unwrap();
        let memory_usage = Gauge::new("yam_memory_usage", "Memory usage in MB").unwrap();

        registry.register(Box::new(cpu_usage.clone())).unwrap();
        registry.register(Box::new(memory_usage.clone())).unwrap();

        Self { registry, cpu_usage, memory_usage }
    }

    pub fn update_metrics(&self, pid: i32) {
        let mut sys = System::new();
        sys.refresh_processes();
        
        if let Some(process) = sys.process(Pid::from(pid as usize)) {
            self.cpu_usage.set(process.cpu_usage() as f64);
            self.memory_usage.set(process.memory() as f64 / 1024.0 / 1024.0);
        }
    }

    pub fn expose_metrics(&self) -> String {
        let encoder = TextEncoder::new();
        let metric_families = self.registry.gather();
        encoder.encode_to_string(&metric_families).unwrap()
    }
}